package com.gbco.intelligentpush.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * @ Author     ：tk.
 * @ Date       ：Created in 11:06 2020/05/23
 * @ Description：网络工具类
 * @ Modified By：
 * @Version: $
 */
@Slf4j
public class HttpUtil {

    //post请求
    public static String post(String url, String data) {
        try {
            URL urlObj = new URL(url);
            URLConnection connection = urlObj.openConnection();
            // 要发送数据出去，必须要设置为可发送数据状态
            connection.setDoOutput(true);
            // 获取输出流
            OutputStream os = connection.getOutputStream();
            // 写出数据
            os.write(data.getBytes("UTF-8"));
            os.close();
            // 获取输入流
            return dealReturn(connection.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    //get请求
    public static String get(String url) {
        try {
            URL urlObj = new URL(url);
            // 开连接
            URLConnection connection = urlObj.openConnection();
            return dealReturn(connection.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //处理返回结果
    public static String dealReturn(InputStream inputStream){

        StringBuilder sb;
        try{
            byte[] b = new byte[1024];
            int len;
            sb = new StringBuilder();
            while ((len = inputStream.read(b)) != -1) {
                sb.append(new String(b, 0, len));
            }
            return sb.toString();
        }catch (IOException e){
            log.error("HttpUtil : 结果处理出错");
        }
        return null;
    }

}
